package com.ruijie.autotest.log.impl.parse;

import com.minelx.landisk.filesystem.core.File;
import com.ruijie.autotest.log.impl.data.Columns;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GridColumnsParser implements IColumnsParser {

	private final String delimiter;

	private final int columnIndex;

	public GridColumnsParser(String delimiter, int columnIndex) {
		this.delimiter = delimiter;
		this.columnIndex = columnIndex;
	}

	@Override
	public Columns parseColumns(File columnFile) {
		try {
			String[] lines = columnFile.read().split("\r\n|\n");
			List<String> columnNames = new ArrayList<>();
			for (String line : lines) {
				String[] cells = line.split(delimiter);
				columnNames.add(cells[columnIndex]);
			}
			// TODO 2021/1/11 memory usage here might be too heavy.
			// TODO Builder instead.
			return new Columns(columnNames.toArray(new String[0]));
		} catch (IOException e) {
			throw new RuntimeException("can't parse: " + columnFile + " to Columns");
		}
	}
}
